import pygame
from random import randint
import tkMessageBox
from pygame.locals import *
pygame.init() 

size = width, height = 480, 480
screen = pygame.display.set_mode(size) 
empty = 0
white=(255,255,255)
black=(0,0,0)
red=(255,0,0)
blue=(0,0,255)
def draw_game():
   pygame.draw.rect(screen, white,(0,0,width,height))
   
   pygame.draw.line(screen,black,(160,0),(160,480),5)
   pygame.draw.line(screen,black,(320,0),(320,480),5)
   pygame.draw.line(screen,black,(0,160),(480,160),5)
   pygame.draw.line(screen,black,(0,320),(480,320),5)
   for row, line in enumerate(state):
        for col, val in enumerate(line):
            if state[row][col] == -1:
              
                upper_left = (col * 160 + 5, row * 160 + 5)
                lower_right = (col * 160 + 155, row * 160 + 155)
                pygame.draw.line(screen, red, upper_left, lower_right, 5)
                            
                upper_right = (col * 160 + 155, row * 160 + 5)
                lower_left = (col * 160 + 5, row * 160 + 155)
                pygame.draw.line(screen, red, upper_right, lower_left, 5)
            elif state[row][col] == 1:
                
                rect = (col * 160 + 5, row * 160 + 5, 150, 150)
                pygame.draw.ellipse(screen, blue, rect, 5)
                pygame.display.flip()
               
def draw_O():
     
          while True:
                    row = randint(0,2)
                    col = randint(0,2)
                 
                    if state[row][col] == 0:
                              state[row][col] = 1
                              break
          draw_game()
          pygame.display.flip()
            
def begin():
                  global state
                  state = [[empty] * 3,[empty] * 3,[empty] * 3]
                  draw_game()
                  pygame.display.flip()
begin() 
while True: 
    event=pygame.event.wait()
    
    pos = None
    if event.type == QUIT:
            quit()        
    elif event.type == MOUSEBUTTONDOWN and event.button == 1:
       
        pos = (event.pos[1]/160, event.pos[0]/160)
        row,col=pos
        state[row][col] = -1
        draw_game()
        print pos
        draw_O()
    pygame.display.flip() 
